<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <button id="start">开始闪烁</button>
    <button id="stop">停止闪烁</button>
    <script>
      function randomNum(min, max) {
        var num = parseInt(Math.random() * (max - min)) + min;
        var num = num.toString(16);
        var num2 = (parseInt(Math.random() * (max - min)) + min).toString(16);
        return num + num2;
      }
      var timer;
      //如果在 startbtn.onclick 的函数体内声明timer， 仅是它的局域变量 ，其他的函数不能用 所以声明为全局
      var startbtn = document.getElementById("start");
      startbtn.onclick = function () {
        timer = setInterval(function () {
          console.log(randomNum(0, 15));
          document.body.style.background = `#${randomNum(0, 15)}${randomNum(
            0,
            15
          )}${randomNum(0, 15)}`;
        }, 500);
      };

      var stopbtn = document.getElementById("stop");
      stopbtn.onclick = function () {
        clearInterval(timer);
      };
    </script>
  </body>
</html>
